package com.cwh.taskcenter.domain.engine.rule.executor;

import com.alibaba.qlexpress4.Express4Runner;
import com.alibaba.qlexpress4.QLOptions;
import com.cwh.taskcenter.domain.engine.rule.context.TaskRuleContext;
import com.cwh.taskcenter.domain.engine.rule.parser.ConditionTree;
import com.cwh.taskcenter.domain.engine.rule.parser.ConditionTreeParser;
import com.cwh.taskcenter.domain.task.model.TaskRule;
import com.cwh.taskcenter.task.dto.event.UserBehaviorEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cwh
 */
@Slf4j
@Component
public class RuleExecutor {

    @Autowired
    private Express4Runner runner;



    public Boolean execute(UserBehaviorEvent event, TaskRule taskRule) {
        // 根据事件类型获取上下文
        TaskRuleContext context = new TaskRuleContext();
        context.setUserId(event.getUserId());
        context.setTaskId(taskRule.getTaskId());
        context.setEventType(event.getEventType());
        context.setBizId(event.getBizId());
        context.setBizValue(event.getBizValue());
        context.setBizType(event.getBizType());
        return executeCondition(taskRule, context);
    }

    public Boolean executeCondition(TaskRule taskRule, TaskRuleContext context) {
        ConditionTree conditionTree = taskRule.getConditionTree();
        // 条件解析
        String express = ConditionTreeParser.parseConditionTree(conditionTree);
        log.info("条件表达式：{}",express);
        Map<String,Object> expressContext = new HashMap<>();
        expressContext.put("context",context);
        expressContext.put(context.getBizType(),context.getBizValue());
        QLOptions options = QLOptions.builder().attachments(expressContext)
                .build();
        return (Boolean) runner.execute(express, expressContext, options).getResult();
    }

}
